import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    value: '',
    // 建议数据列表数据
    suggestList: [],
    // 搜索历史列表
    kwList: []
  }

  computed = {
    isShowHistory () {
      if (this.value.length <= 0) {
        return true
      }
      return false
    }
   }

  methods = {
    // 输入内容变化时，获取数据的关键字
    onChange(e) {
      this.value = e.detail.trim()

      if (e.detail.trim().length <= 0) {
        this.suggestList = []
        return
      }

      this.getSuggestList(e.detail)
    },

    // 触发搜索事件到商品列表
    onSearch(e) {
      // e.detail 就是最新的搜索关键字
      var kw = e.detail.trim()
      // 如果搜索关键词为空，则阻止跳转
      if (kw.length <= 0) {
        return
      }

      // 如果本地存储中已经有某个关键字，这时候就不在进行存储
      if (this.kwList.indexOf(kw) === -1) {
        this.kwList.unshift(kw)
      }

      // 让本地存储的搜索历史始终只保存 10 条数据
      this.kwList = this.kwList.slice(0, 10)
      wepy.setStorageSync('kw', this.kwList)

      wepy.navigateTo({
        url: '/pages/goods_list?query=' + kw
      })  
    },
    onCancel() {
      this.suggestList = []
    },
    
    goGoodsDetail (goodsId) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?goods_id=' + goodsId
      })
    },

    goGoodsList (name) {
      wepy.navigateTo({
        url: '/pages/goods_list?query=' + name
      })
    },

    clearHistory () {
      this.kwList = []
      wepy.setStorageSync('kw', [])
    }
  }

  // 获取搜索建议列表的数据
  async getSuggestList(searchStr) {
    const { data: res } = await wepy.get('/goods/qsearch', { query: searchStr })

    // 判断返回的数据是否成功
    if (res.meta.status !== 200) {
      return wepy.baseToast()
    }

    this.suggestList = res.message
    this.$apply()
  }

  onLoad() {
    const kw = wx.getStorageSync('kw') || []
    this.kwList = kw

    console.log(this.kwList)
  }
}
